﻿using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace TST.SharePointObjects
{
    internal class FeatureDefinitionWebApplicationReferences : ObjectReferenceList
    {
        public FeatureDefinitionWebApplicationReferences(LicensingMode licensingMode)
            : base(licensingMode)
        {
        }

        public override ObjectReferenceType ObjectReferenceType
        {
            get { return ObjectReferenceType.FeatureDefinitionWebApplication; }
        }

        internal void Add(SiteObjectList objects, SPWebApplication webApplication)
        {
            String adminUrl = String.Empty;
            Microsoft.SharePoint.Administration.SPAdministrationWebApplication centralWeb = SPAdministrationWebApplication.Local;
            using (SPSite centralAdmin = centralWeb.Sites[0])
            {
                adminUrl = centralAdmin.Url;
            }
            foreach (SPFeature feature in webApplication.Features)
            {
                SiteObject siteObject = objects.GetItemById(feature.DefinitionId.ToString("B"));
                if (siteObject != null && siteObject.Index)
                {
                    if (Globals.MatchingScope(siteObject, webApplication))
                    {
                        string refId = Globals.GetReferenceId(siteObject, feature);
                        ObjectReference newReference = new ObjectReference(webApplication.Id.ToString("B"), webApplication.Name, refId, ObjectReferenceType.FeatureDefinitionWebApplication);
                        newReference.Url = string.Format("{0}/_admin/ManageWebAppFeatures.aspx?WebApplicationId={1}", adminUrl, webApplication.ToString());
                        newReference.SiteTitle = String.Empty;
                        newReference.SiteUrl = String.Empty;
                        newReference.ListTitle = String.Empty;
                        newReference.ListUrl = String.Empty;
                        Add(newReference);
                    }
                }
            }
        }

    }
}
